package com.yi.wood.gob.gate.handler;

import com.alibaba.fastjson.JSONObject;
import com.yi.wood.base.GobEventEnum;
import com.yi.wood.cache.CacheEntity;
import com.yi.wood.cache.UserCache;
import com.yi.wood.gob.gate.cal.GobCoupleRoom;
import com.yi.wood.room.Battlefield;
import com.yi.wood.room.CoupleRoom;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * Created by moyi on 2018/10/11 17:23
 *
 * @author moyi
 * Gob 事件处理
 */
@Service
public class GobEventHandler implements EventHandler{

    private static final Logger LOG = LoggerFactory.getLogger(GobEventHandler.class);

    @Resource
    private UserCache userCache;

    /**
     * 获取战场对象
     */
    private Battlefield battlefield = Battlefield.getGobBattlefield();

    @Override
    public void execute(JSONObject jsonData, ChannelHandlerContext ctx) {
        // 验证token
        String token = jsonData.getString("token");
        CacheEntity cacheEntity = userCache.get(token);
        Long id = cacheEntity.getId();
        // 判断事件
        String event = jsonData.getString("event");

        GobEventEnum gobEventEnum = GobEventEnum.getEnum(event);
        switch (gobEventEnum){
            case ADD:
                GobCoupleRoom gobCoupleRoom = (GobCoupleRoom)battlefield.get(id);
                gobCoupleRoom.setDefenseId(id);
                battlefield.gobAddBattle(gobCoupleRoom);
                break;
            case CREATE:
                GobCoupleRoom room = new GobCoupleRoom();
                battlefield.gobAddBattle(room);
                break;
            case EXIT:
                exitRoom(id);
                break;
            case NEXT:


                break;
            default:
                LOG.info("不支持{}命令...",gobEventEnum.getEvent());
                break;
        }
    }

    public boolean existRoom(Long id){
        CoupleRoom room = (CoupleRoom) battlefield.get(id);
        if (room == null){
            return false;
        }
        return room.getAttackId().equals(id) || room.getDefenseId().equals(id);
    }

    public void exitRoom(Long id){
        battlefield.remove(id);
    }
}
